package com.magicstone.common.Licence.service;
import java.security.*;

import javax.crypto.*;

public class DESer {
	private static final String DES_KEY = "i'm a good man!";
    private Cipher encryptCipher = null;
    private Cipher decryptCipher = null;

    public DESer(){
        this(DES_KEY);
    }

    public DESer(String strKey) {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        Key key;
        try {
            key = getKey(strKey.getBytes());
            encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key);
            decryptCipher = Cipher.getInstance("DES");
            decryptCipher.init(Cipher.DECRYPT_MODE, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public byte[] encrypt(byte[] arrB){
        byte[] s = null ;
        try {
            s = encryptCipher.doFinal(arrB);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return s ;
    }

    public String encrypt(String strIn) {
        return Convertor.bytesToHexString(encrypt(strIn.getBytes()));
    }

    public byte[] decrypt(byte[] arrB)  {
        byte[] s = null ;
        try {
            s = decryptCipher.doFinal(arrB);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return s ;
    }

    public String decrypt(String strIn){
        return new String(decrypt(Convertor.hexStringToBytes(strIn)));
    }

    private Key getKey(byte[] arrBTmp) {
        // 创建一个空的8位字节数组（默认值为0）
        byte[] arrB = new byte[8];
        // 将原始字节数组转换为8位
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }
        // 生成密钥
        Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
        return key;
    }

}
